package org.bbx.autoops.utils;


import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.auth.GlobalCredentials;
import com.huaweicloud.sdk.rms.v1.region.RmsRegion;
import com.huaweicloud.sdk.rms.v1.*;
import com.huaweicloud.sdk.rms.v1.model.*;
import io.micrometer.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class ListAllResourcesUtil {

    @Value("${metric.config.region}")
    private String region;


    @Value("${hw.ak}")
    private String ak;

    @Value("${hw.sk}")
    private String sk;


    public ListAllResourcesResponse listAllResources(String marker,String type) {


        ICredential auth = new GlobalCredentials()
                .withAk(ak)
                .withSk(sk);

        RmsClient client = RmsClient.newBuilder()
                .withCredential(auth)

                .withRegion(RmsRegion.valueOf(region))
                .build();
        ListAllResourcesRequest request = new ListAllResourcesRequest();
        request.withLimit(200);

        if (!StringUtils.isBlank(marker)) {
            request.withMarker(marker);
        }

        if (!StringUtils.isBlank(type)) {
            request.withType(type);
        }

        ListAllResourcesResponse response = client.listAllResources(request);
        return response;
    }


    public @NotNull Map<String, ResourceEntity> getResourcesMap() {
        String marker = null;
        Map<String, ResourceEntity> collect = new HashMap<>();
        List<String> typeList = getTypeList();

        for (String i : typeList) {
            ListAllResourcesResponse l = listAllResources(marker,i);
            Map<String, ResourceEntity> tmp = l.getResources().stream().collect(Collectors.toMap(ResourceEntity::getId, r -> r));
            collect.putAll(tmp);
            marker = l.getPageInfo().getNextMarker();

        }



        return collect;
    }

    @NotNull
    private static List<String> getTypeList() {
        List<String> typeList = new ArrayList<>();
        typeList.add("ecs.cloudservers");
        typeList.add("rds.instances");
        typeList.add("vpc.bandwidths");
        typeList.add("elb.loadbalancers");
        typeList.add("nat.natGateways");
        typeList.add("cbh.instance");
        typeList.add("cce.clusters");
        typeList.add("cce.nodes");
        typeList.add("dcs.redis");
        typeList.add("gaussdb.instance");
        typeList.add("gaussdbformysql.instance");
        typeList.add("waf.instance");
        return typeList;
    }


}
